package org.jeecg.modules.demo.pusettlement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.puInvoice.service.IPuInvoiceService;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.pusettlement.entity.PuSettlement;
import org.jeecg.modules.demo.pusettlement.entity.PuSettlementVo;
import org.jeecg.modules.demo.pusettlement.service.IPuSettlementService;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

 /**
 * @Description: 采购结算
 * @Author: jeecg-boot
 * @Date:   2021-12-06
 * @Version: V1.0
 */
@Api(tags="采购结算")
@RestController
@RequestMapping("/pusettlement/puSettlement")
@Slf4j
public class PuSettlementController extends JeecgController<PuSettlement, IPuSettlementService> {
	@Autowired
	private IPuSettlementService puSettlementService;
	@Autowired
	private IPuBuyOrderService puBuyOrderService;
	@Autowired
	private IPuInvoiceService puInvoiceService;
	 @Autowired
	 private ISysBaseAPI sysBaseAPI;


	/**
	 * 分页列表查询
	 *
	 * @param puSettlement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "采购结算单-分页列表查询")
	@ApiOperation(value="采购结算单-分页列表查询", notes="采购结算单-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="yunxiao/pubuySettlementOrder/PuBuyOrderSettlementList")
	public Result<?> queryPageList(PuSettlement puSettlement,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		try{
			QueryWrapper<PuSettlement> queryWrapper = QueryGenerator.initQueryWrapper(puSettlement, req.getParameterMap());
			queryWrapper.ne("DJLX",2);
			Page<PuSettlement> page = new Page<PuSettlement>(pageNo, pageSize);
			IPage<PuSettlement> pageList = puSettlementService.page(page, queryWrapper);
			return Result.OK(pageList);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(300,"网络故障！");
		}
	}

	 @PostMapping(value = "/getYkTotailByOrder")
	 public String getYkTotailByOrder(@RequestParam(name="str",required=true)String str){
		 Gson gson = new Gson();
		 Map map = new HashMap();
		 try{
			 Map<String,Double>  map1 = puSettlementService.getYkTotailByOrder(str);
			 map.put("code",200);
			 map.put("message","查询成功！");
			 map.put("ykTotal",map1.get("YKTOTAL"));
			 map.put("poOrder",map1.get("PO_ORDER"));
			 String json = gson.toJson(map);
			 return json;
		 }catch (Exception e){
			 e.printStackTrace();
			 map.put("code",500);
			 map.put("message","系统错误！");
			 String json = gson.toJson(map);
			 return json;
		 }
	 }
	@PostMapping(value = "/getWriteOffDetails")
	public String getWriteOffDetails(@RequestBody PuSettlement puSettlement){
		Gson gson = new Gson();
		Map map = new HashMap();
		try{
			List<PuSettlement> puSettlements = puSettlementService.getWriteOffDetails(puSettlement);
			map.put("code",200);
			map.put("message","查询成功！");
			map.put("puSettlements",puSettlements);
			String json = gson.toJson(map);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			map.put("code",500);
			map.put("message","系统错误！");
			String json = gson.toJson(map);
			return json;
		}
	}

	/**
	 *   添加
	 *
	 * @param puSettlement
	 * @return
	 */
	@AutoLog(value = "采购结算单-添加")
	@ApiOperation(value="采购结算单-添加", notes="采购结算单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody PuSettlement puSettlement,HttpServletRequest req) {
		try{
			if(puSettlement.getCotoo()==null){
				puSettlement.setCotoo("false");
			}
			if(puSettlement.getCotoo().equals("true")){
				if(puSettlement.getAccessory()==null){
					return Result.error(300,"请上传货权转移证明！");
				}
			}else{
				puSettlement.setAccessory("");
			}
			puSettlement.setId(null);
			puSettlement.setShenhe(0);
			puSettlement.setShanchu(0);
			puSettlement.setCreateTime(new Date());
			String tenantId = req.getHeader("tenant-id");
			String precode = puBuyOrderService.getTeantCodeById(Integer.parseInt(tenantId)).toUpperCase();
			String number = puSettlementService.getMaxCode();
			Map<String,String> codeMap = new HashMap<>();
			codeMap.put("maxCode",StringUtils.isBlank(number)?null:number);
			String name =precode+ "JS_";
			String resultCode = generateOddUtil.createCode(codeMap,name);
			puSettlement.setPusNo(resultCode);
			if(puSettlementService.addPuSettlement(puSettlement)){
				return Result.OK("成功！");
			}
			return Result.error(300,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	@PostMapping(value = "/addHPuSettlement")
	public Result<?> addHPuSettlement(@RequestBody PuSettlementVo puSettlementVo,HttpServletRequest req){
		try{
			String tenantId = req.getHeader("tenant-id");
			if(puSettlementService.addHPuSettlement(puSettlementVo,tenantId)){
				return Result.OK("成功！");
			}
			return Result.error(500,"失败！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统故障！");
		}
	}


	@PostMapping(value = "/getYjByOrder")
	public Result<?> getYjByOrder(@RequestParam(name="str",required=true)String str,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){
		try{
			Page<PuSettlement> page = new Page<PuSettlement>(pageNo, pageSize);
			List<PuSettlement> settlements = puSettlementService.getYjByOrder(str,page);
			return Result.OK(settlements);
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}

	}


	 /**
	  *  审核
	  *
	  * @param puSettlement
	  * @return
	  */
	 @AutoLog(value = "采购结算单-审核")
	 @ApiOperation(value="采购结算单-审核", notes="采购结算单-审核")
	 @PostMapping(value = "/checkSettlement")
	 public Result<?> checkSettlement(@RequestBody PuSettlement puSettlement) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(puSettlement.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if (puSettlement.getShenhe()==1){
				 return Result.error(300,"已审核，无需重复审核！");
			 }
			 if(puSettlementService.checkSettlement(puSettlement)){
				 return Result.OK("审核成功!");
			 }

			 return Result.error(500,"审核失败！");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误！");
		 }
	 }
	 /**
	  *  弃审
	  *
	  * @param puSettlement
	  * @return
	  */
	 @AutoLog(value = "采购结算单-弃审")
	 @ApiOperation(value="采购结算单-弃审", notes="采购结算单-弃审")
	 @PostMapping(value = "/waiveChecKSettlement")
	 public Result<?> waiveChecKSettlement(@RequestBody PuSettlement puSettlement) {
		 try{
			 // 获取登录用户信息
			 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			 if(!sysUser.getId().equals(puSettlement.getSaleman())){
				 return Result.error(500,"您不是当前单据的指定审核人！");
			 }
			 if (puSettlement.getShenhe()==0){
				 return Result.error(300,"请先审核单据！");
			 }

			 if (puSettlement.getDjlx()==1){
				 return Result.error(300,"该单为预结算单，无法弃审！");
			 }
			 List<String> ids = puInvoiceService.selectByPusNo(puSettlement.getPusNo());
			 if(!ids.isEmpty()){
			 	return Result.error(300,"已生成发票，无法弃审！");
			 }
			 if(puSettlementService.waiveChecKSettlement(puSettlement)){
				 return Result.OK("弃审成功!");
			 }

			 return Result.error(500,"弃审失败！");
		 }catch (Exception e){
			 e.printStackTrace();
			 return Result.error(500,"系统错误！");
		 }
	 }
	/**
	 *  编辑
	 *
	 * @param puSettlement
	 * @return
	 */
	@AutoLog(value = "采购结算单-编辑")
	@ApiOperation(value="采购结算单-编辑", notes="采购结算单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody PuSettlement puSettlement) {
		try{
			if(puSettlement.getCotoo().equals("true")){
				if(puSettlement.getAccessory()==null){
					return Result.error(300,"请上传货权转移证明！");
				}
			}else{
				puSettlement.setAccessory("");
			}
			puSettlement.setCreateTime(new Date());
			if(puSettlementService.editPuSettlement(puSettlement)){
				return Result.OK("编辑成功!");
			}
			return Result.error(300,"网络故障！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	@PostMapping(value = "/getJSTotail")
	public String getJSTotail(@RequestBody PuSettlement settlement){
		Gson gson = new Gson();
		Map map = new HashMap();
		try{
			Double d = puSettlementService.getTotailByNumber(settlement);
			map.put("code",200);
			map.put("message","查询成功！");
			map.put("yu",d);
			String json = gson.toJson(map);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			map.put("code",500);
			map.put("message","系统错误！");
			String json = gson.toJson(map);
			return json;
		}
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购结算单-通过id删除")
	@ApiOperation(value="采购结算单-通过id删除", notes="采购结算单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		try{
			PuSettlement puSettlement = puSettlementService.getById(id);
			if (puSettlement.getShenhe()==1){
				return Result.error("单据已审核，无法删除！");
			}
			//if (puSettlement.getDjlx()==1){
				//return Result.error("单据为预结算单，删除预开发票，此单据自动删除！");
			//}

			puSettlement.setShanchu(1);
			if(puSettlementService.deletePuSettlement(puSettlement)){
				return  Result.OK("删除成功！");
			}
			return Result.error(500,"删除失败！");
		}catch (Exception e){
			e.printStackTrace();
			return Result.error(500,"系统错误！");
		}
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "采购结算单-批量删除")
	@ApiOperation(value="采购结算单-批量删除", notes="采购结算单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.puSettlementService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "采购结算单-通过id查询")
	@ApiOperation(value="采购结算单-通过id查询", notes="采购结算单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		PuSettlement puSettlement = puSettlementService.getById(id);
		if(puSettlement==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(puSettlement);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param puSettlement
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PuSettlement puSettlement) {
        return super.exportXls(request, puSettlement, PuSettlement.class, "采购结算");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, PuSettlement.class);
    }


}
